package cn.clickmed.plugin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONException;
import com.dj.websign.WebSignClient;

import android.widget.Toast;
import cn.clickmed.DaTong.Configure;
import cn.clickmed.certification.Cert;
import cn.com.jit.mctk.auth.exception.PNXAuthClientException;
import cn.com.jit.mctk.cert.exception.PNXCertException;
import cn.com.jit.mctk.common.util.CommonUtil;

public class CAPlugin extends CordovaPlugin {
	public static final String tag = "CAPlugin";
	public static final String DELETE_CA = "ca";
	public static final String CLOSE_PROXY = "close";
	public static final String SEAL = "seal";
	private WebSignClient client;
	//private CertManager certManager;// 证书管理器
	private String sealsXml;
	List<Map<String, String>> seals = null;// 印章列表
	HashMap<String, String> addseal = null;// 签名信息

	String sealName;
	String sealPosition;
	String originText;
	String sealId;

	@Override
	public boolean execute(String action, String rawArgs,
			CallbackContext callbackContext) throws JSONException {
		if (action.equals(DELETE_CA)) {
			boolean success = false;
			try {
				success = Cert.getInstance().deleteCert(cordova.getActivity());
			} catch (PNXCertException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (success) {
				Toast.makeText(cordova.getActivity(), "证书已删除",
						Toast.LENGTH_LONG).show();
				cordova.getActivity().finish();
			} else {
				Toast.makeText(cordova.getActivity(), "证书删除失败，请重试",
						Toast.LENGTH_LONG).show();
			}
		} else if (action.equals(CLOSE_PROXY)) {
			if (!CommonUtil.isEmpty(Cert.getInstance().getProxyUrl())) {
				try {
					Cert.getInstance().closeProxy();
				}  catch (PNXAuthClientException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				cordova.getActivity().finish();
			}
		} /*else if (action.equals(SEAL)) {
			MCTKContext.getInstance(cordova.getActivity());
			client = new WebSignClient();
			client.setUrl_adress(Configure.SEAL_SERVER_URL);// 设置印章服务器地址
			JSONArray array = new JSONArray(rawArgs);
			JSONObject obj = array.getJSONObject(0);
			sealName = obj.getString("sealName");
			sealPosition = obj.getString("sealposition");
			originText = obj.getString("originText");
			certManager = new CertManager();
			CertEntry cert = null;
			try {
				cert = certManager.getCertList().get(0);
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(cordova.getActivity(), "获取证书失败，自动退出应用",
						Toast.LENGTH_LONG).show();
			}
			if (cert == null) {
				Toast.makeText(cordova.getActivity(), "获取证书失败，自动退出应用",
						Toast.LENGTH_LONG).show();
				cordova.getActivity().finish();
			}
			sealsXml = client.getSealList();
			Log.i(tag, "已获取到印章：" + sealsXml);
			seals = StringXmlUtil.parseGetSeals(sealsXml);
			if (seals == null) {
				Toast.makeText(cordova.getActivity(), "获取印章失败,请联系系统管理员",
						Toast.LENGTH_LONG).show();
				return true;
			}
			sealId = seals.get(0).get("sealId");
			Log.i(tag, "正在盖章。。。。");
			new DlgWait().ShowWait(cordova.getActivity(), "请等待。。。", "正在盖章。。。",
					new InterFaceWait() {
						public void WaitFucn() {
							String sealres = client.addSeal(createAddSealXml());
							System.out.println(sealres);
							addseal = StringXmlUtil.parseAddSeal(sealres);
						}
					});
			if (addseal != null) {
				Toast.makeText(cordova.getActivity(), "盖章成功！",
						Toast.LENGTH_LONG).show();
			    PluginResult mPlugin = new PluginResult(PluginResult.Status.OK,  
			    		addseal.get("sealRes"));  
                mPlugin.setKeepCallback(true);  
                callbackContext.sendPluginResult(mPlugin);
			} else {
				Toast.makeText(cordova.getActivity(), "盖章失败，请重试",
						Toast.LENGTH_LONG).show();
			}
		}*/

		return true;
	}

	protected String createAddSealXml() {
		StringBuffer sb = new StringBuffer(
				"<?xml version='1.0' encoding='UTF-8'?>");
		sb.append("<root>");
		sb.append("<info>");
		sb.append("<user>");
		sb.append("<password>");
		sb.append(Configure.PASSWORD);// 密码
		sb.append("</password>");
		sb.append("</user>");
		sb.append("<seal>");
		sb.append("<sealId>");
		sb.append(sealId);// 印章id
		sb.append("</sealId>");
		sb.append("<sealName>");
		sb.append(sealName);// 盖章名称,（签名标识）
		sb.append("</sealName>");
		sb.append("<seal_position>");
		sb.append(sealPosition);// 印章位置
		sb.append("</seal_position>");
		sb.append("<seal_x>");
		sb.append("0");// 偏移位置
		sb.append("</seal_x>");
		sb.append("<seal_y>");
		sb.append("0");
		sb.append("</seal_y>");
		sb.append("<oriData>");
		sb.append(originText);// 原文
		sb.append("</oriData>");
		sb.append("</seal>");
		sb.append("</info>");
		sb.append("</root>");
		return sb.toString();
	}
}
